package com.getword.service.impl;

import com.getword.mongodao.ArticleRepository;
import com.getword.service.ArticleStatisticsService;
import com.getword.web.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class ArticleStatisticsServiceImpl implements ArticleStatisticsService {
    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public Result todayCount() {
        // 获取今天凌晨时刻
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String s = sdf.format(new Date());
        Date date = new Date();
        try {
            date = sdf.parse(s);   // 凌晨时刻
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 大于date的文章
        Long count = articleRepository.countArticlesByReleaseTimeGreaterThan(date);
        return Result.success(count);
    }

    @Override
    public Result sevenDayCount() {
        Map<String, Object> res = new HashMap<>();
        long[] result = new long[7];
        // 获取指定某天的发布量  如：2019,4，24
        LocalDate now = LocalDate.now();
        for (int i = 0; i < 7; i++) {
            result[i] = getCountADay(now.getYear(), now.getMonthValue(), now.getDayOfMonth());
            String key = now.getYear() + "-" + now.getMonthValue() + "-" + now.getDayOfMonth();
            long value = result[i];
            res.put("day"+(7-i), new HashMap<String,Object>(){{
                put("date", key);
                put("count", value);
            }});
            now = now.minusDays(1);
        }
        return Result.success(res);
    }

    public long getCountADay(int year, int month, int day) {
        LocalDateTime fromL = LocalDateTime.of(year, month, day, 0, 0, 0);
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = fromL.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
        Date from = Date.from(zdt.toInstant());

        LocalDateTime toL = LocalDateTime.of(year, month, day + 1, 0, 0, 0);
        ZoneId zoneId2 = ZoneId.systemDefault();
        ZonedDateTime zdt2 = toL.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
        Date to = Date.from(zdt2.toInstant());

        Long count = articleRepository.countArticlesByReleaseTimeBetween(from, to);
        return count;
    }
}
